<template>
  <view class="add-page">
    <!-- 安全提示 -->
    <view class="security-tips">
      <view class="tips-icon">!</view>
      <view class="tips-content">
        <text class="tips-title">安全提示</text>
        <text class="tips-text"
          >为了保护你的账号安全：
          1.这里保存的密码不建议直接使用。
          2.建议根据个人习惯去掉密码中的关键部分。 3.不建议保留完整密码。
          4.请妥善保管您的密码信息，防止信息泄露导致被盗用。</text
        >
      </view>
    </view>

    <!-- 表单区域 -->
    <view class="form-container">
      <!-- 表单项 -->
      <view class="form-item">
        <text class="form-label">标题</text>
        <view class="input-container">
          <input
            class="form-input"
            v-model="formData.title"
            placeholder="请输入标题"
          />
        </view>
      </view>

      <view class="divider"></view>

      <view class="form-item">
        <text class="form-label">账号</text>
        <view class="input-container">
          <input
            class="form-input"
            v-model="formData.account"
            placeholder="请输入账号"
          />
        </view>
      </view>

      <view class="divider"></view>

      <view class="form-item">
        <text class="form-label">密码</text>
        <view class="input-container">
          <input
            class="form-input"
            v-model="formData.password"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请输入密码"
          />
        </view>
        <view class="action-icons">
          <view class="icon" @tap="togglePassword">
            <image
              :src="
                showPassword
                  ? '/static/svg/eye-open.svg'
                  : '/static/svg/eye-close.svg'
              "
              mode="aspectFit"
              class="icon-img"
            />
          </view>
          <view class="icon" @tap="toggleGenerator">
            <image
              :src="
                showGenerator
                  ? '/static/svg/caret-up.svg'
                  : '/static/svg/caret-down.svg'
              "
              mode="aspectFit"
              class="icon-img"
            />
          </view>
        </view>
      </view>

      <!-- 随机生成密码折叠区域 -->
      <view class="password-generator" v-if="showGenerator">
        <view class="generator-title">
          <text>随机生成密码</text>
        </view>
        <view class="password-options">
          <view class="option-group">
            <text class="option-label">组成：</text>
            <view class="tags-container">
              <view
                class="tag"
                :class="{ active: passwordOptions.includeNumbers }"
                @tap="
                  passwordOptions.includeNumbers =
                    !passwordOptions.includeNumbers
                "
              >
                数字
              </view>
              <view
                class="tag"
                :class="{ active: passwordOptions.includeLowercase }"
                @tap="
                  passwordOptions.includeLowercase =
                    !passwordOptions.includeLowercase
                "
              >
                小写字母
              </view>
              <view
                class="tag"
                :class="{ active: passwordOptions.includeUppercase }"
                @tap="
                  passwordOptions.includeUppercase =
                    !passwordOptions.includeUppercase
                "
              >
                大写字母
              </view>
              <view
                class="tag"
                :class="{ active: passwordOptions.includeSymbols }"
                @tap="
                  passwordOptions.includeSymbols =
                    !passwordOptions.includeSymbols
                "
              >
                特殊符号
              </view>
            </view>
          </view>

          <view class="option-group">
            <text class="option-label">长度：</text>
            <view class="length-control">
              <view class="length-btn" @tap="decreaseLength">-</view>
              <text class="length-value">{{ passwordOptions.length }}</text>
              <view class="length-btn" @tap="increaseLength">+</view>
            </view>
          </view>

          <view class="generate-btn-container">
            <view class="generate-btn" @tap="generatePassword">生成密码</view>
          </view>
        </view>
      </view>

      <view class="section-divider"></view>

      <view class="form-item">
        <text class="form-label">备注</text>
        <view class="input-container">
          <textarea
            class="form-textarea"
            v-model="formData.remark"
            placeholder="请输入备注信息"
          />
        </view>
      </view>
    </view>

    <!-- 确认按钮 -->
    <view class="footer-btn-wrapper">
      <button class="submit-btn" @tap="handleSubmit">
        {{ isEdit ? "确认修改" : "确认添加" }}
      </button>
    </view>

    <!-- 错误信息 -->
    <view v-if="errorMessage" class="error-message">
      <text>{{ errorMessage }}</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      formData: {
        id: "",
        title: "",
        account: "",
        password: "",
        remark: "",
      },
      isEdit: false,
      passwordOptions: {
        length: 12,
        includeNumbers: true,
        includeLowercase: true,
        includeUppercase: true,
        includeSymbols: false,
      },
      showPassword: true,
      showGenerator: false,
      errorMessage: "",
    };
  },

  onLoad(options) {
    // 根据是否传入id判断是新增还是编辑
    if (options.id) {
      this.isEdit = true;
      this.getPasswordData();
    } else {
      this.isEdit = false;
      // 清空表单数据
      this.formData = {
        id: "",
        title: "",
        account: "",
        password: "",
        remark: "",
      };
    }
  },
  methods: {
    togglePassword() {
      this.showPassword = !this.showPassword;
    },
    toggleGenerator() {
      this.showGenerator = !this.showGenerator;
    },
    handleSubmit() {
      if (
        !this.formData.title ||
        !this.formData.account ||
        !this.formData.password
      ) {
        this.errorMessage = "请填写完整信息！";
        return;
      }

      try {
        if (this.isEdit) {
          uni.setStorageSync("editingPassword", this.formData);
        } else {
          this.formData.id = this.generateRandomId();
          // 保存到本地存储
          uni.setStorageSync("passwords", this.formData);
        }

        // 显示成功提示
        uni.showToast({
          title: this.isEdit ? "修改成功" : "添加成功",
          icon: "success",
          duration: 1500,
          success: () => {
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          },
        });
      } catch (error) {
        console.error("保存数据失败:", error);
        this.errorMessage = "保存失败，请重试！";
      }
    },
    handleCancel() {
      // 返回上一页
      uni.navigateBack();
    },
    decreaseLength() {
      if (this.passwordOptions.length > 6) {
        this.passwordOptions.length--;
      }
    },
    increaseLength() {
      if (this.passwordOptions.length < 32) {
        this.passwordOptions.length++;
      }
    },
    generatePassword() {
      // 检查是否至少选择了一种字符类型
      if (
        !this.passwordOptions.includeNumbers &&
        !this.passwordOptions.includeLowercase &&
        !this.passwordOptions.includeUppercase &&
        !this.passwordOptions.includeSymbols
      ) {
        this.errorMessage = "请至少选择一种密码字符类型";
        return;
      }

      const numbers = "0123456789";
      const lowercase = "abcdefghijklmnopqrstuvwxyz";
      const uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      const symbols = "!@#$%^&*()_+-=[]{}|;:,.<>?";

      let chars = "";
      if (this.passwordOptions.includeNumbers) chars += numbers;
      if (this.passwordOptions.includeLowercase) chars += lowercase;
      if (this.passwordOptions.includeUppercase) chars += uppercase;
      if (this.passwordOptions.includeSymbols) chars += symbols;

      let password = "";
      for (let i = 0; i < this.passwordOptions.length; i++) {
        const randomIndex = Math.floor(Math.random() * chars.length);
        password += chars[randomIndex];
      }

      this.formData.password = password;
      this.errorMessage = "";

      // 显示成功提示
      uni.showToast({
        title: "密码已生成",
        icon: "success",
        duration: 1500,
      });
    },
    // 生成随机ID
    generateRandomId() {
      return (
        "pwd_" + Date.now() + "_" + Math.random().toString(36).substr(2, 9)
      );
    },
    // 获取密码数据
    async getPasswordData() {
      const editingPassword = JSON.parse(uni.getStorageSync("editingPassword"));
      console.log("passwords", editingPassword);

      if (editingPassword) {
        this.formData = { ...editingPassword };
      } else {
        uni.showToast({
          title: "数据不存在",
          icon: "none",
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
/* 
 * 此页面使用了全局按钮样式，包括:
 * - .submit-btn: 提交按钮样式
 * - .generate-btn: 可考虑也迁移到全局样式
 * 详见: @/styles/button.scss
 */
.add-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.security-tips {
  margin: 20rpx;
  padding: 20rpx;
  background-color: #fff7e6;
  border-radius: 8rpx;
  display: flex;
  align-items: flex-start;
  border: 1rpx solid #ffe7ba;
}

.tips-icon {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background-color: #fa8c16;
  color: #fff;
  text-align: center;
  line-height: 40rpx;
  font-weight: bold;
  margin-right: 20rpx;
  flex-shrink: 0;
}

.tips-content {
  flex: 1;
}

.tips-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #fa8c16;
  margin-bottom: 8rpx;
  display: block;
}

.tips-text {
  font-size: 24rpx;
  color: #666;
  line-height: 1.5;
}

.form-container {
  background-color: #ffffff;
  margin-top: 10rpx;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 30rpx 40rpx;
  position: relative;
}

.divider {
  height: 1rpx;
  background-color: #e5e5e5;
  margin-left: 40rpx;
}

.section-divider {
  height: 20rpx;
  background-color: #f5f5f5;
  width: 100%;
}

.form-label {
  width: 100rpx;
  font-size: 30rpx;
  color: #333;
  font-weight: 400;
}

.input-container {
  flex: 1;
}

.form-input {
  font-size: 30rpx;
  color: #333;
  width: 100%;
  height: 35px;
  padding: 10rpx 0;
  border: none;
  outline: none;
  background-color: transparent;
  box-sizing: border-box;
  /* 解决动态type边框问题 */
  border-width: 0;
  border-style: none;
  border-color: transparent;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
}

/* 针对不同平台的输入框样式覆盖 */
/* #ifdef H5 */
::v-deep input {
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
}
/* #endif */

/* 小程序 */
/* #ifdef MP-WEIXIN */
::v-deep input {
  border-width: 0 !important;
  border-style: none !important;
}
/* #endif */

.form-textarea {
  width: 100%;
  height: 200rpx;
  font-size: 30rpx;
  line-height: 1.5;
  border: none;
  outline: none;
  background-color: transparent;
  padding: 0;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
}

.action-icons {
  display: flex;
  align-items: center;
}

.icon {
  width: 40rpx;
  height: 40rpx;
  margin-left: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-img {
  width: 38rpx;
  height: 38rpx;
  opacity: 0.6;
  transition: all 0.3s;
}

// 密码生成器样式
.password-generator {
  background-color: #f9f9f9;
  padding: 20rpx 40rpx 30rpx;
  border-top: 1rpx solid #e5e5e5;
}

.generator-title {
  margin-bottom: 20rpx;
  text-align: center;

  text {
    font-size: 30rpx;
    font-weight: 500;
    color: #1890ff;
  }
}

.password-options {
  margin-top: 10rpx;
}

.option-group {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.option-label {
  font-size: 26rpx;
  color: #666;
  margin-right: 20rpx;
  width: 80rpx;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  flex: 1;
}

.tag {
  background-color: #f0f0f0;
  color: #666;
  padding: 6rpx 20rpx;
  border-radius: 30rpx;
  font-size: 24rpx;
  margin-right: 16rpx;
  margin-bottom: 16rpx;
  border: 2rpx solid transparent;
}

.tag.active {
  background-color: #e6f7ff;
  color: #1890ff;
  border-color: #91d5ff;
}

.length-control {
  display: flex;
  align-items: center;
}

.length-btn {
  width: 50rpx;
  height: 50rpx;
  background-color: #f0f0f0;
  border-radius: 50%;
  text-align: center;
  line-height: 46rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.length-value {
  padding: 0 30rpx;
  font-size: 30rpx;
}

.generate-btn-container {
  display: flex;
  justify-content: center;
  margin-top: 20rpx;
}

.generate-btn {
  background-color: #1890ff;
  color: #fff;
  padding: 16rpx 60rpx;
  border-radius: 30rpx;
  font-size: 28rpx;
  display: inline-block;
}

.submit-button-container {
  padding: 60rpx 40rpx;
}

.error-message {
  margin: 20rpx 40rpx;
  background-color: #fff2f0;
  color: #f5222d;
  padding: 20rpx;
  border-radius: 8rpx;
  text-align: center;
  border: 1rpx solid #ffccc7;
}

::placeholder {
  color: #999;
}
</style> 